package com.lhkj.ct.wechat.controller;

import com.lhkj.ct.wechat.base.model.vo.WxPayNotifyV3Response;
import com.lhkj.ct.wechat.service.WeChatPayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * @author : hwx
 * @version ：2.0
 * @Description :
 * @date : 2024-04-01
 */
@RestController
@RequestMapping("/wechat/pay")
public class WxMpPayController{

    private static final Logger logger = LoggerFactory.getLogger(WxMpPayController.class);

    @Resource
    private WeChatPayService weChatPayService;

    @RequestMapping("/notify")
    public String parseOrderNotifyResult(HttpServletRequest request) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
            //sb为微信返回的xml
            String notifyData = sb.toString();
            String timeStamp = request.getHeader("Wechatpay-Timestamp");
            String nonce = request.getHeader("Wechatpay-Nonce");
            String signature = request.getHeader("Wechatpay-Signature");
            String serial = request.getHeader("Wechatpay-Serial");
            logger.debug("微信支付异步通知请求参数：{}", notifyData);
            logger.debug("timeStamp：{}, nonce：{}, signature：{}, serial：{}", timeStamp, nonce, signature, serial);
            weChatPayService.parseOrderNotifyV3Result(notifyData,timeStamp,nonce,signature,serial);
            return WxPayNotifyV3Response.success("成功");
        } catch (Exception ex) {
            ex.printStackTrace();
            return WxPayNotifyV3Response.fail("失败");
        }
    }
}
